package com.jbm.enterapplication.doorjurisd;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jbm.connet.UtlisNetWork;
import com.jbm.db.MyOpenLog;
import com.jbm.db.MySqliUtlis;
import com.jbm.db.OpenKey;
import com.jbm.enterapplication.InterfaceMa;
import com.jbm.enterapplication.R;
import com.jbm.enterapplication.utlisclass.SaveOpenKeyManage;
import com.jbm.le.DoorEvent;
import com.jbm.le.OpenCtrl;
import com.jbm.onehome.common.OHInterface;
import com.jbm.onehome.iface.IEGLog;
import com.jbm.onehome.iface.IEGLogCtrl;
import com.jbm.onehome.iface.IEGuardKey;
import com.jbm.onehome.iface.IEGuardKeyCtrl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;


/**
 * Created by 家帮忙 on 2017/2/17.
 */

public class DoorOpenBlue {


    private  String vivler;
    private float Volume;
    private  ArrayList<IEGuardKey> arr;
    private ArrayList<IEGuardKey> ArrayListIEKey;
    private  SharedPreferences.Editor sharlog;

    private Vibrator vibratorr;
    private Context con;
    private IEGuardKeyCtrl iekc;
    private IEGuardKey egkeys;
    private SoundPool sp;
    private Handler handlerpuball;
    private String tableopemerr = "";
    private TextView te;
    private TextView texts;
    private Timer ti;
    private ImageView images;
    public static final int ERROR=0001;
    public static final int SUCESS=0002;
    public static final int ERROS=0004;
    private int is_open;
    private InterfaceMa<IEGLogCtrl> interfaceMa;

    public DoorOpenBlue() {
    }
    public  DoorOpenBlue(Context c, Handler handlerpuball, InterfaceMa<IEGLogCtrl> interfaceMa) {
        this.con = c;
        this.handlerpuball = handlerpuball;
        this.interfaceMa=interfaceMa;
       ArrayListIEKey = new ArrayList<>();
        AudioManager manager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Volume = currentVolume / (float) maxVolume;
        PackageManager packageManager=c.getPackageManager();
        try {
            PackageInfo vivle = packageManager.getPackageInfo(c.getPackageName(), 0);
             vivler = vivle.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void OpenDoorGather(String name, TextView textView, final Context context, Activity activity, ImageView image) {
        this.te=textView;
        OpenCtrl ctrl = new OpenCtrl();
        arr =   new SaveOpenKeyManage(con).setgainOpenKey();
        if (arr==null){
            Toast.makeText(context, "没有开门权限", Toast.LENGTH_SHORT).show();
            return;}
        if (arr.size() > 0) {
            iekc = new IEGuardKeyCtrl();
            iekc.EGKlist = new IEGuardKey[arr.size()];
            for(int i=0;i<arr.size();i++) {
                if (arr.get(i).open_count == 0) {
                    return;
                } else {
                    iekc.EGKlist[i] = arr.get(i);
                }
            }
                     setViratoor();
            OpenKey.getinstant().setName("按钮开");
            OpenKey.getinstant().setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
                FuMbleOpenDoor(ctrl, context, activity, "按钮",iekc,image);
            }
    }

String info;
    private void FuMbleOpenDoor(OpenCtrl ctrl, final Context context, Activity activity, final String sign, IEGuardKeyCtrl iekc, final ImageView image) {



        ctrl.Open(1333, 3, iekc, context, activity, new DoorEvent() {
            @Override
            public void OpenSuccess(IEGuardKey egkey, String mac) {
                //开门成功
//                SetCheckoutOpenCount(egkey);
                egkeys = egkey;
                is_open = 1;
                tableopemerr = "开门成功";
                sp = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
                sp.load(con, R.raw.dingdong, 1);
                sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                    @Override
                    public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                        soundPool.play(i, Volume, Volume, 1, 0, 1);
                    }
                });

               handlerpuball.sendMessage( handlerpuball.obtainMessage(SUCESS,""));
                getkaimen();
            }

            @Override
            public void OpenFailed(IEGuardKey egkey, String mac) {
                //开门失败
                egkeys = egkey;
                is_open = 0;
                tableopemerr = "开门失败";
                OPenEerr();
                handlerpuball.sendMessage( handlerpuball.obtainMessage(ERROR,tableopemerr));
                getkaimen();
            }

            @Override
            public void NotFound() {
                //未找到蓝牙设备
                is_open = 0;
                tableopemerr = "未找到蓝牙设备";
                handlerpuball.sendMessage( handlerpuball.obtainMessage(ERROR,tableopemerr));
                getkaimen();
            }

            @Override
            public void OtherError(String errorinfo) {
                //所有关于蓝牙的相关报错信息
                is_open = 0;
                tableopemerr = errorinfo;
                handlerpuball.sendMessage( handlerpuball.obtainMessage(ERROS,tableopemerr));
                getkaimen();
            }

            @Override
            public void OpenStatus(String info) {
                //再有们的情况下开门给用户的提示数据
                tableopemerr=info;
                handlerpuball.sendMessage( handlerpuball.obtainMessage(ERROR,tableopemerr));
            }
        }, false);

    }
    private void setViratoor() {//震动
        vibratorr = (Vibrator) con.getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {100, 400, 100, 400}; // 停止 开启 停止 开启
        vibratorr.vibrate(pattern, -1);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                vibratorr.cancel();
            }
        }, 500);

    }


    private void SetCheckoutOpenCount(IEGuardKey egkey){
        for(int i=0;i<arr.size();i++){
            if (arr.get(i).open_key.equals(egkey.open_key)){
                if (egkey.open_total!=-1){
                    int count= arr.get(i).open_count-1;
                    egkey.open_count=count;
                    egkeys=egkey;
                }else{

                }
            }
        }
        if (egkey.open_total==-1){
            egkeys=egkey;
        }
        ArrayListIEKey.add(egkeys);
        new SaveOpenKeyManage(con).setsaveOpenkey(ArrayListIEKey);
    }

    public void OPenEerr(){
        sp = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
        sp.load(con, R.raw.ddd, 1);
        sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                soundPool.play(i, Volume, Volume, 1, 0, 1);
            }
        });
    }




    public void getkaimen() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String date = formatter.format(curDate);
        try {
            if (tableopemerr.equals("")) {
                return;
            }
            if (egkeys == null) {
                MySqliUtlis.getInstance(con).Opendatakey(OHInterface.getG_server().login_id, 0, 0, 0, date, date, is_open, 0, Build.MODEL + Build.VERSION.RELEASE, OpenKey.getinstant().getName(), OpenKey.getinstant().getTime(), date, "sales"+tableopemerr+vivler);
            } else {
                MySqliUtlis.getInstance(con).Opendatakey(egkeys.login_id, egkeys.eguard_id, egkeys.egkey_id, egkeys.open_count, date, date, is_open, 0, Build.MODEL + Build.VERSION.RELEASE, OpenKey.getinstant().getName(), OpenKey.getinstant().getTime(), date, "sales"+tableopemerr+vivler);
            }
            ArrayList<MyOpenLog> listopen = MySqliUtlis.getInstance(con).ShowddataOpenKey();
            IEGLogCtrl ieglog = new IEGLogCtrl();
            ieglog.EGLlist = new IEGLog[listopen.size()];
            for (int i = 0; i < listopen.size(); i++) {
                ieglog.EGLlist[i] = new IEGLog();
                ieglog.EGLlist[i].login_id = listopen.get(i).getLogin_id();
                ieglog.EGLlist[i].eguard_id = listopen.get(i).getEguard_id();
                ieglog.EGLlist[i].egkey_id = listopen.get(i).getEgkey_id();
                ieglog.EGLlist[i].last_count = listopen.get(i).getLast_count();
                ieglog.EGLlist[i].open_date = listopen.get(i).getOpen_date();
                ieglog.EGLlist[i].create_date = listopen.get(i).getCreate_date();
                ieglog.EGLlist[i].is_open = listopen.get(i).getIs_open();
                ieglog.EGLlist[i].try_cnt = listopen.get(i).getTry_cnt();//重复开门次数
                ieglog.EGLlist[i].phone_module = listopen.get(i).getPhone_module();
                ieglog.EGLlist[i].open_type = listopen.get(i).getOpen_type();
                ieglog.EGLlist[i].ord_date = listopen.get(i).getOrd_date();
                ieglog.EGLlist[i].call_date = listopen.get(i).getCall_date();
                ieglog.EGLlist[i].errinfo = listopen.get(i).getError();
            }
            int mode= UtlisNetWork.getnetwokstate(con);
            if (mode==0) {
                interfaceMa.onSuccess(ieglog,true);

            } else if (mode==1){
                interfaceMa.onSuccess(ieglog,true);

            }else if (mode==-1){
                return;
            }
        } catch (Exception e) {

        }
    }



    public  void getkaimens(){

        try {
            ArrayList<MyOpenLog> listopen =  MySqliUtlis.getInstance(con).ShowddataOpenKey();
            if (listopen.size() == 0) {
                return;
            } else {
                IEGLogCtrl ieglog = new IEGLogCtrl();
                ieglog.EGLlist = new IEGLog[listopen.size()];
                for (int i = 0; i < listopen.size(); i++) {
                    ieglog.EGLlist[i] = new IEGLog();
                    ieglog.EGLlist[i].login_id = listopen.get(i).getLogin_id();
                    ieglog.EGLlist[i].eguard_id = listopen.get(i).getEguard_id();
                    ieglog.EGLlist[i].egkey_id = listopen.get(i).getEgkey_id();
                    ieglog.EGLlist[i].last_count = listopen.get(i).getLast_count();
                    ieglog.EGLlist[i].open_date = listopen.get(i).getOpen_date();
                    ieglog.EGLlist[i].create_date = listopen.get(i).getCreate_date();
                    ieglog.EGLlist[i].is_open = listopen.get(i).getIs_open();
                    ieglog.EGLlist[i].try_cnt = listopen.get(i).getTry_cnt();//重复开门次数
                    ieglog.EGLlist[i].phone_module = listopen.get(i).getPhone_module();
                    ieglog.EGLlist[i].open_type = listopen.get(i).getOpen_type();
                    ieglog.EGLlist[i].ord_date = listopen.get(i).getOrd_date();
                    ieglog.EGLlist[i].call_date = listopen.get(i).getCall_date();
                    ieglog.EGLlist[i].errinfo = listopen.get(i).getError();
                }
                int mode= UtlisNetWork.getnetwokstate(con);
                if (mode==0) {
                    interfaceMa.setError(ieglog,true);
                } else if (mode==1){
                    interfaceMa.setError(ieglog,true);

                }else if (mode==-1){
                    return;
                }
            }

        } catch (Exception e) {

        }


    }




















}
